//
//  AnswerViewController.m
//  TestSchool
//
//  Created by wuxiaoquan on 12-11-2.
//  Copyright (c) 2012年 yaoxia. All rights reserved.
//

#import "QuestionViewController.h"
#import "UserManager.h"
#import "AnswerViewController.h"
#import "MoreInfoViewController.h"
#import "AppDelegate.h"

@interface QuestionViewController ()

@end

@implementation QuestionViewController

@synthesize testNameLabel,testName,testId,questionList,questionView,answerBtn;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"More" style:UIBarButtonItemStylePlain target:self action:@selector(goMoreInfo:)];
    self.testNameLabel.text = self.testName;
    [self addRoundBound:self.questionView];
    [self setQuestion:0];
}

-(IBAction)goMoreInfo:(id)sender
{
    MoreInfoViewController *detailController = [[MoreInfoViewController alloc]initWithNibName:@"MoreInfoViewController" bundle:nil];
    detailController.questionId = [[self.questionList objectAtIndex:[UserManager getCurrentUser].currentQuestionIndex ]objectForKey:@"questionid"];
    [self.navigationController pushViewController:detailController animated:YES];
}

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    NSLog(@"问题页面显示");
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    self.testNameLabel = nil;
    self.testName = nil;
    request = nil;
    self.testId = nil;
    self.questionView = nil;
    self.questionList = nil;
    self.answerBtn = nil;
  
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

-(IBAction)answerOne:(id)sender
{
    
    int index = [UserManager getCurrentUser].currentQuestionIndex;
    if ([[[self.questionList objectAtIndex:index] objectForKey:@"answered"]intValue] != 0) {
        //已经回答过了
        UIAlertView *alert = [[UIAlertView alloc]
                              initWithTitle:@"Message"
                              message:@"This question is already been answered!"
                              delegate:self
                              cancelButtonTitle:@"OK"
                              otherButtonTitles:nil];
        [alert show];
        return;
    }
    NSLog(@"回答问题");
    AnswerViewController *detailController = [[AnswerViewController alloc]initWithNibName:@"AnswerViewController" bundle:nil];
    detailController.questionList = self.questionList;
    detailController.testId = self.testId;
    [self.navigationController pushViewController:detailController animated:YES];
}

-(IBAction)preQuestion:(id)sender
{
    int temp = [UserManager getCurrentUser].currentQuestionIndex - 1;
    if (temp >= 0 && temp < self.questionList.count) {
        [self setQuestion:temp];
    }
    else
    {
        UIAlertView *alert = [[UIAlertView alloc]
                              initWithTitle:@"Message"
                              message:@"This is the first Question"
                              delegate:self
                              cancelButtonTitle:@"OK"
                              otherButtonTitles:nil];
        [alert show];
    }
}
-(IBAction)nextQuestion:(id)sender
{
    int temp = [UserManager getCurrentUser].currentQuestionIndex + 1;
    if (temp >= 0 && temp < self.questionList.count) {
        if ([[[self.questionList objectAtIndex:[UserManager getCurrentUser].currentQuestionIndex] objectForKey:@"answered"]intValue] == 0) {
            UIAlertView *alert = [[UIAlertView alloc]
                                  initWithTitle:@"Message"
                                  message:@"Please answer this question first!"
                                  delegate:self
                                  cancelButtonTitle:@"OK"
                                  otherButtonTitles:nil];
            [alert show];
            return;
        }
        else
        {
            [self setQuestion:temp];
        }
        
    }
    else
    {
        UIAlertView *alert = [[UIAlertView alloc]
                              initWithTitle:@"Message"
                              message:@"This is the last Question"
                              delegate:self
                              cancelButtonTitle:@"OK"
                              otherButtonTitles:nil];
        [alert show];
    }
}

-(void)setQuestion:(int)index
{
    if (self.questionList.count <= 0) {
        return;
    }
    [UserManager getCurrentUser].currentQuestionIndex = index;
    self.title = [NSString stringWithFormat:@"%d of %d",[UserManager getCurrentUser].currentQuestionIndex + 1,self.questionList.count];
    
    [self showWaitView:nil];
    
    
    //NSString * URL_LOGIN = @"http://218.24.94.212/Test/getone.jsp";
    AppDelegate *delegate=(AppDelegate*)[[UIApplication sharedApplication]delegate];
    NSString * URL_LOGIN = [NSString stringWithFormat:@"%@/Test/getone.jsp",delegate.baseUrl];
    
    NSURL *url = [NSURL URLWithString:URL_LOGIN];
    request = [ASIFormDataRequest requestWithURL:url];
    
    [request setPostValue:[[self.questionList objectAtIndex:index] objectForKey:@"questionid"]   forKey:@"questionid"];
    [request setPostValue:[UserManager getCurrentUser].userId forKey:@"userid"];
    [request setPostValue:self.testId forKey:@"testid"];
    
    [request setCompletionBlock:^{
        [self hideWaitView];
        // Use when fetching text data
        NSString *responseString = [request responseString];
        
        //NSLog(@"responseString = %@",responseString);//显示收到的信息
        
        id json = [responseString JSONValue];
        //NSLog(@"meg = %@",[json objectForKey:@"drugInfo"]);
        if ([[json objectForKey:@"code"]intValue] == 500) {
            UIAlertView * messageAlert = [[UIAlertView alloc]
                                          initWithTitle:@"Message"
                                          message:[NSString stringWithFormat:@"%@",[json objectForKey:@"message"]]
                                          delegate:self
                                          cancelButtonTitle:@"OK"
                                          otherButtonTitles:nil];
            [messageAlert show];
            return ;
        }
        [self doLeftInAnimation:self.questionView];
        self.questionView.text = [json objectForKey:@"questioncontent"];
        
        // Use when fetching binary data
        //NSData *responseData = [request responseData];
    }];
    [request setFailedBlock:^{
        [self hideWaitView];
        NSError *error = [request error];
        
        NSLog(@"error = %@",error);
        UIAlertView *alert = [[UIAlertView alloc]
                              initWithTitle:@"Network error"
                              message:@"Please check your network"
                              delegate:self
                              cancelButtonTitle:@"OK"
                              otherButtonTitles:nil];
        [alert show];
    }];
    [request startAsynchronous];

}
-(void)doLeftInAnimation:(UIView *)v
{
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    [UIView setAnimationDuration:1.0f];
    [UIView setAnimationTransition:UIViewAnimationTransitionFlipFromLeft forView:v cache:YES];
    // operation>>>
    [self.view exchangeSubviewAtIndex:0 withSubviewAtIndex:1];
    // end<<<<<<
    [UIView commitAnimations];
}

@end
